<template>
    <view style="padding: 15px;">
        <div style="padding: 10px; background: white;">
            <div class="table table-bordered" style="width: 100%; display: inline;">
                <div class="tr">
                    <div class="td">
                        <div>促销方式说明：</div>
                        <div>一个商品只能选择一种促销方式，每种促销类型至少设置一个触发促销条件，最多支持5个促销梯度。</div>
                    </div>
                </div>
                <div class="tr">
                    <div class="td">
                        <div>示例1：商品下单金额满###元减#元</div>
                        <div>
                            可录入值：<br/>
                            商品下单金额满10元减1元<br/>
                            商品下单金额满20元减3元<br/>
                            商品下单金额满30元减5元<br/>
                            商品下单金额满40元减7元<br/>
                            商品下单金额满50元减10元
                        </div>
                    </div>
                </div>
                <div class="tr">
                    <div class="td">
                        <div>示例2：商品下单数量满###件减打#折</div>
                        <div>
                            可录入值：<br/>
                            商品下单数量满10件减打0.95折<br/>
                            商品下单数量满20件减打0.90折<br/>
                            商品下单数量满50件减打0.70折<br/>
                            #折值最大是1，当为1时表示不打折。
                        </div>
                    </div>
                </div>
                <div class="tr">
                    <div class="td">
                        <div>示例3：商品下单金额每满###元减#元</div>
                        <div>
                            可录入值：<br/>
                            商品下单金额每满5元减1元<br/>
                            此时只需录一条记录即可，当商品下单金额满10元时自动减2元，满15元时减3元以此类推。
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <u-form ref="validateFormRef" :model="validateForm.value" :label-width="150">

            <u-form-item label="促销类型" prop="type" required>
                <u-input type="select" :select-open="validateForm.controls.type.isShow" v-model="validateForm.controls.type.textDesc"
                         placeholder="请选择促销类型" @click="validateForm.controls.type.isShow = true; $forceUpdate();"></u-input>
            </u-form-item>

            <u-form-item label="①###值" prop="if1" required>
                <u-input v-model="validateForm.value.if1" placeholder="请输入###的值"/>
            </u-form-item>

            <u-form-item label="①#值" prop="result1" required v-if="'03,13,23,33,43'.indexOf(validateForm.value.type) == -1">
                <u-input v-model="validateForm.value.result1" placeholder="请输入#的值"/>
            </u-form-item>

            <u-form-item label="①#值" prop="result1" required v-if="'03,13,23,33,43'.indexOf(validateForm.value.type) !== -1">
                <div style="padding: 7px;">
                    <myImg :obj="validateForm.controls.result1" :sysFile="{fkId: validateForm.value.result1}" :key="validateForm.controls.result1.timestamp"
                           :customStyle="'pointer-events: none; height: 100px;  width:100px; background-size: cover; background-repeat: no-repeat; background-position: center;'"
                           :defaultUrl="'/pages/sub/sub2-store-platform/static/default-image/goods.jpg'"
                           :imageView="'imageView2/1/w/200/h/200'"
                           v-if="validateForm.value.result1"
                    ></myImg>

                    <u-button size="mini"
                              v-if="!validateForm.value.result1"
                              @click="selectPresent('result1')">
                        添加赠品
                    </u-button>

                    <u-button size="mini" v-if="validateForm.value.result1"
                              @click="clearResult('result1')">
                        删除
                    </u-button>
                </div>
            </u-form-item>

            <u-form-item label="②###值" prop="if2">
                <u-input v-model="validateForm.value.if2" placeholder="请输入###的值"/>
            </u-form-item>

            <u-form-item label="②#值" prop="result2" v-if="'03,13,23,33,43'.indexOf(validateForm.value.type) == -1">
                <u-input v-model="validateForm.value.result2" placeholder="请输入#的值"/>
            </u-form-item>

            <u-form-item label="②#值" prop="result2" v-if="'03,13,23,33,43'.indexOf(validateForm.value.type) !== -1">
                <div style="padding: 7px;">
                    <myImg :obj="validateForm.controls.result2" :sysFile="{fkId: validateForm.value.result2}" :key="validateForm.controls.result2.timestamp"
                           :customStyle="'pointer-events: none; height: 100px;  width:100px; background-size: cover; background-repeat: no-repeat; background-position: center;'"
                           :defaultUrl="'/pages/sub/sub2-store-platform/static/default-image/goods.jpg'"
                           :imageView="'imageView2/1/w/200/h/200'"
                           v-if="validateForm.value.result2"
                    ></myImg>

                    <u-button size="mini"
                              v-if="!validateForm.value.result2"
                              @click="selectPresent('result2')">
                        添加赠品
                    </u-button>

                    <u-button size="mini" v-if="validateForm.value.result2"
                              @click="clearResult('result2')">
                        删除
                    </u-button>
                </div>
            </u-form-item>

            <u-form-item label="③###值" prop="if3">
                <u-input v-model="validateForm.value.if3" placeholder="请输入###的值"/>
            </u-form-item>

            <u-form-item label="③#值" prop="result3" v-if="'03,13,23,33,43'.indexOf(validateForm.value.type) == -1">
                <u-input v-model="validateForm.value.result3" placeholder="请输入#的值"/>
            </u-form-item>

            <u-form-item label="③#值" prop="result3" v-if="'03,13,23,33,43'.indexOf(validateForm.value.type) !== -1">
                <div style="padding: 7px;">
                    <myImg :obj="validateForm.controls.result3" :sysFile="{fkId: validateForm.value.result3}" :key="validateForm.controls.result3.timestamp"
                           :customStyle="'pointer-events: none; height: 100px;  width:100px; background-size: cover; background-repeat: no-repeat; background-position: center;'"
                           :defaultUrl="'/pages/sub/sub2-store-platform/static/default-image/goods.jpg'"
                           :imageView="'imageView2/1/w/200/h/200'"
                           v-if="validateForm.value.result3"
                    ></myImg>

                    <u-button size="mini"
                              v-if="!validateForm.value.result3"
                              @click="selectPresent('result3')">
                        添加赠品
                    </u-button>

                    <u-button size="mini" v-if="validateForm.value.result3"
                              @click="clearResult('result3')">
                        删除
                    </u-button>
                </div>
            </u-form-item>

            <u-form-item label="④###值" prop="if4">
                <u-input v-model="validateForm.value.if4" placeholder="请输入###的值"/>
            </u-form-item>

            <u-form-item label="④#值" prop="result4" v-if="'03,13,23,33,43'.indexOf(validateForm.value.type) == -1">
                <u-input v-model="validateForm.value.result4" placeholder="请输入#的值"/>
            </u-form-item>

            <u-form-item label="④#值" prop="result4" v-if="'03,13,23,33,43'.indexOf(validateForm.value.type) !== -1">
                <div style="padding: 7px;">
                    <myImg :obj="validateForm.controls.result4" :sysFile="{fkId: validateForm.value.result4}" :key="validateForm.controls.result4.timestamp"
                           :customStyle="'pointer-events: none; height: 100px;  width:100px; background-size: cover; background-repeat: no-repeat; background-position: center;'"
                           :defaultUrl="'/pages/sub/sub2-store-platform/static/default-image/goods.jpg'"
                           :imageView="'imageView2/1/w/200/h/200'"
                           v-if="validateForm.value.result4"
                    ></myImg>

                    <u-button size="mini"
                              v-if="!validateForm.value.result4"
                              @click="selectPresent('result4')">
                        添加赠品
                    </u-button>

                    <u-button size="mini" v-if="validateForm.value.result4"
                              @click="clearResult('result4')">
                        删除
                    </u-button>
                </div>
            </u-form-item>

            <u-form-item label="⑤###值" prop="if5">
                <u-input v-model="validateForm.value.if5" placeholder="请输入###的值"/>
            </u-form-item>

            <u-form-item label="⑤#值" prop="result5" v-if="'03,13,23,33,43'.indexOf(validateForm.value.type) == -1">
                <u-input v-model="validateForm.value.result5" placeholder="请输入#的值"/>
            </u-form-item>

            <u-form-item label="⑤#值" prop="result5" v-if="'03,13,23,33,43'.indexOf(validateForm.value.type) !== -1">
                <div style="padding: 7px;">
                    <myImg :obj="validateForm.controls.result5" :sysFile="{fkId: validateForm.value.result5}" :key="validateForm.controls.result5.timestamp"
                           :customStyle="'pointer-events: none; height: 100px;  width:100px; background-size: cover; background-repeat: no-repeat; background-position: center;'"
                           :defaultUrl="'/pages/sub/sub2-store-platform/static/default-image/goods.jpg'"
                           :imageView="'imageView2/1/w/200/h/200'"
                           v-if="validateForm.value.result5"
                    ></myImg>

                    <u-button size="mini"
                              v-if="!validateForm.value.result5"
                              @click="selectPresent('result5')">
                        添加赠品
                    </u-button>

                    <u-button size="mini" v-if="validateForm.value.result5"
                              @click="clearResult('result5')">
                        删除
                    </u-button>
                </div>
            </u-form-item>

            <u-form-item label="开始时间" prop="startTime" required>
                <u-input type="select" :select-open="validateForm.controls.startTime.isShow"
                         v-model="validateForm.value.startTime" placeholder="请选择开始时间"
                         @click="validateForm.controls.startTime.isShow = true; $forceUpdate();"/>
            </u-form-item>

            <u-form-item label="结束时间" prop="endTime" required>
                <u-input type="select" :select-open="validateForm.controls.endTime.isShow"
                         v-model="validateForm.value.endTime" placeholder="请选择结束时间"
                         @click="validateForm.controls.endTime.isShow = true; $forceUpdate();"/>
            </u-form-item>

            <u-form-item label="状态" prop="status" required>
                <u-input type="select" :select-open="validateForm.controls.status.isShow" v-model="validateForm.controls.status.textDesc"
                         placeholder="请选择状态" @click="validateForm.controls.status.isShow = true; $forceUpdate();"></u-input>
            </u-form-item>
        </u-form>

        <u-button type="error" @click="submit">提交</u-button>

        <u-select mode="single-column" label-name="name" value-name="code" :mask-close-able="false"
                  v-model="validateForm.controls.type.isShow" :list="validateForm.controls.type.options"
                  :default-value="validateForm.controls.type.defaultValue"
                  @cancel="validateForm.controls.type.isShow = false; $forceUpdate();"
                  @confirm="UFormUtil.selectSingleColumnConfirm($event, validateForm.controls.type)"></u-select>

        <u-select mode="single-column" label-name="name" value-name="code" :mask-close-able="false"
                  v-model="validateForm.controls.status.isShow" :list="validateForm.controls.status.options"
                  :default-value="validateForm.controls.status.defaultValue"
                  @cancel="validateForm.controls.status.isShow = false; $forceUpdate();"
                  @confirm="UFormUtil.selectSingleColumnConfirm($event, validateForm.controls.status)"></u-select>

        <u-picker mode="time" :mask-close-able="false" v-model="validateForm.controls.startTime.isShow"
                  :default-time="validateForm.value.startTime" :params="pickerFormatDatetime"
                  @cancel="validateForm.controls.startTime.isShow = false; $forceUpdate();"
                  @confirm="UFormUtil.timeConfirm($event, validateForm.controls.startTime)"></u-picker>

        <u-picker mode="time" :mask-close-able="false" v-model="validateForm.controls.endTime.isShow"
                  :default-time="validateForm.value.endTime" :params="pickerFormatDatetime"
                  @cancel="validateForm.controls.endTime.isShow = false; $forceUpdate();"
                  @confirm="UFormUtil.timeConfirm($event, validateForm.controls.endTime)"></u-picker>
    </view>
</template>

<script>
    import {CommonUtil} from "@/dev/core/utils/common.util";
    import {SysDictionaryService} from "@/dev/services/sys-dictionary.service";
    import {UFormUtil} from "@/dev/core/utils/u-form.util";
    import {TbStorePromotionService} from "@/dev/services/tb-store-promotion.service";
    import myImg from '@/components/my-img'

    export default {
        data() {
            return {
                isSubmit: false,  // 是否提交事件
                validateForm: {
                    value: {
                        id: CommonUtil.randomUUID(),
                        storeId: this.globalVariable.userInfo.tbStore.id,
                        goodsId: '',
                        goodsSpecificationId: '',
                        goodsColorId: '',
                        type: '',
                        if1: '',
                        if2: '',
                        if3: '',
                        if4: '',
                        if5: '',
                        result1: '',
                        result2: '',
                        result3: '',
                        result4: '',
                        result5: '',
                        startTime: '',
                        endTime: '',
                        status: '0'
                    },
                    rules: {
                        type: [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                            {
                                trigger: ['blur'],
                                asyncValidator: (rule, value, callback) => {
                                    if (!this.isSubmit) {
                                        // 改变促销类型重置所有状态
                                        this.validateForm.value.result1 = '';
                                        this.validateForm.value.result2 = '';
                                        this.validateForm.value.result3 = '';
                                        this.validateForm.value.result4 = '';
                                        this.validateForm.value.result5 = '';
                                        this.$forceUpdate();
                                    }
                                    this.isSubmit = false;
                                    callback()
                                }
                            }
                        ],
                        if1: [
                            {
                                pattern: /^(([0-9]+\\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\\.[0-9]+)|([0-9]*[1-9][0-9]*))$/,
                                message: '请输入有效的价格!',
                                trigger: ['change', 'blur']
                            }
                        ],
                        if2: [
                            {
                                pattern: /^(([0-9]+\\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\\.[0-9]+)|([0-9]*[1-9][0-9]*))$/,
                                message: '请输入有效的价格!',
                                trigger: ['change', 'blur']
                            }
                        ],
                        if3: [
                            {
                                pattern: /^(([0-9]+\\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\\.[0-9]+)|([0-9]*[1-9][0-9]*))$/,
                                message: '请输入有效的价格!',
                                trigger: ['change', 'blur']
                            }
                        ],
                        if4: [
                            {
                                pattern: /^(([0-9]+\\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\\.[0-9]+)|([0-9]*[1-9][0-9]*))$/,
                                message: '请输入有效的价格!',
                                trigger: ['change', 'blur']
                            }
                        ],
                        if5: [
                            {
                                pattern: /^(([0-9]+\\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\\.[0-9]+)|([0-9]*[1-9][0-9]*))$/,
                                message: '请输入有效的价格!',
                                trigger: ['change', 'blur']
                            }
                        ],
                        result1: [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                        ],
                        startTime: [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                            {
                                trigger: ['blur'],
                                asyncValidator: (rule, value, callback) => {
                                    if (this.validateForm.value.startTime && this.validateForm.value.endTime) {
                                        let startTime = new Date(this.validateForm.value.startTime).getTime();
                                        let endTime = new Date(this.validateForm.value.endTime).getTime();
                                        if (startTime > endTime) {
                                            callback(new Error('开始时间不能大于结束时间！'));
                                        } else {
                                            callback()
                                        }
                                    } else {
                                        callback()
                                    }
                                }
                            }
                        ],
                        endTime: [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                            {
                                trigger: ['blur'],
                                asyncValidator: (rule, value, callback) => {
                                    if (this.validateForm.value.startTime && this.validateForm.value.endTime) {
                                        let startTime = new Date(this.validateForm.value.startTime).getTime();
                                        let endTime = new Date(this.validateForm.value.endTime).getTime();
                                        if (startTime > endTime) {
                                            callback(new Error('开始时间不能大于结束时间！'));
                                        } else {
                                            callback()
                                        }
                                    } else {
                                        callback()
                                    }
                                }
                            }
                        ],
                        status: [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                            {
                                trigger: ['blur'],
                                asyncValidator: (rule, value, callback) => {
                                    // 订单促销，先判断是否有启用的促销活动
                                    if (value === '1' && !this.validateForm.value.goodsSpecificationId && !this.validateForm.value.goodsColorId) {
                                        new TbStorePromotionService().canEnable({
                                            storeId: this.validateForm.value.storeId
                                        }).then(result => {
                                            if (result) {
                                                callback(new Error('订单促销已存在启用的记录，请先禁用掉！'));
                                            } else {
                                                callback()
                                            }
                                        });
                                    } else {
                                        callback()
                                    }
                                }
                            }
                        ],
                    }
                }
            }
        },
        components: {
            myImg
        },
        onShow() {
            const _self = this;
            console.log(this.validateForm);
            _self.$forceUpdate();
        },
        onReady() {
            const _self = this;
            this.validateForm.value.goodsId = this.urlParams.goodsId;
            this.validateForm.value.goodsSpecificationId = this.urlParams.goodsSpecificationId;
            this.validateForm.value.goodsColorId = this.urlParams.goodsColorId;
            new SysDictionaryService().optionList('tb_store_promotion@type', this.urlParams.excludeSubCods).then(result => {
                UFormUtil.setOptions(_self.validateForm.controls.type, result);
                _self.$forceUpdate();
            });
            new SysDictionaryService().optionList('status', null).then(result => {
                UFormUtil.setOptions(_self.validateForm.controls.status, result);
                _self.$forceUpdate();
            });
        },
        methods: {
            selectPresent(result) {
                this.navigateTo('/pages/sub/sub2-store-platform/store-platform/store-platform-store-manage/store-platform-store-present/store-platform-store-present-select/index', null, {
                    obj: this.validateForm.value,
                    attrName: result
                });
            },
            clearResult(result) {
                const _self = this;
                this.validateForm.value[result] = '';
                _self.$forceUpdate();
            },
            submit() {
                const _self = this;
                this.isSubmit = true;
                this.$refs.validateFormRef.validate(valid => {
                    if (valid) {
                        console.log('验证通过', _self.validateForm.value);
                        let data = _self.validateForm.value;
                        if ((data.if2 && !data.result2) || (!data.if2 && data.result2)) {
                            CommonUtil.alert("请检查每一行的促销条件和结果是否同时存在值");
                            return;
                        }
                        if ((data.if3 && !data.result3) || (!data.if3 && data.result3)) {
                            CommonUtil.alert("请检查每一行的促销条件和结果是否同时存在值");
                            return;
                        }
                        if ((data.if4 && !data.result4) || (!data.if4 && data.result4)) {
                            CommonUtil.alert("请检查每一行的促销条件和结果是否同时存在值");
                            return;
                        }
                        if ((data.if5 && !data.result5) || (!data.if5 && data.result5)) {
                            CommonUtil.alert("请检查每一行的促销条件和结果是否同时存在值");
                            return;
                        }

                        CommonUtil.alert({
                            title: '提示！',
                            content: '确认提交吗？',
                            showCancel: true, // 是否显示取消按钮
                            success: function (res) {
                                if (res.cancel) { // 点击取消,默认隐藏弹框
                                } else { // 点击确定
                                    new TbStorePromotionService().saveTbStorePromotion(data).then(result => {
                                        CommonUtil.toastNavigateBack('保存成功');
                                        // 新增商品时，商品规格添加促销方式时
                                        if (_self.objParams) {
                                            _self.objParams.tbStorePromotion = result;
                                        }
                                    });
                                }
                            }
                        });
                    } else {
                        console.log('验证失败');
                    }
                });
            }
        }
    };
</script>

<style lang="scss" scoped>
</style>
